#!/usr/bin/env python3

import argparse
import os
import re
import pendulum

def parse_time(string):
	match = re.match(r'(\d{4}\d{2}\d{2}\d{2})(\d{2})?', string)
	if match.group(2):
		return pendulum.from_format(string, 'YYYYMMDDHHmm')
	else:
		return pendulum.from_format(string, 'YYYYMMDDHH')

parser = argparse.ArgumentParser(description='Write observation data to database.')
parser.add_argument('--synop-root')
parser.add_argument('--raob-root')
parser.add_argument('--amdar-root')
parser.add_argument('--profiler-root')
parser.add_argument('--start-time', required=True, type=parse_time)
parser.add_argument('--end-time', required=True, type=parse_time)
parser.add_argument('--interval-hours', required=True, type=float)
parser.add_argument('--mongo-uri', required=True)
parser.add_argument('--mongo-db', required=True)
parser.add_argument('--mongo-col', required=True)
parser.add_argument('--data-translate-exe', required=True)
args = parser.parse_args()

data_translate = args.data_translate_exe

for time in pendulum.period(args.start_time, args.end_time).range('hours', args.interval_hours):
	if args.synop_root != None:
		synop_file = f'{args.synop_root}/{time.format("YYYYMMDDHHmm")}.xml'
		if not os.path.isfile(synop_file):
			print(f'[Warning]: {synop_file} does not exist.')
		else:
			os.system(f'time {data_translate} -r synop_cimiss_xml -w mongo -i {synop_file} --mongo-uri {args.mongo_uri} --mongo-db {args.mongo_db} --mongo-col {args.mongo_col}')
	if args.raob_root != None:
		raob_file = f'{args.raob_root}/{time.format("YYYYMMDDHH")}.xml'
		if not os.path.isfile(raob_file):
			print(f'[Warning]: {raob_file} does not exist.')
		else:
			os.system(f'time {data_translate} -r raob_cimiss_xml -w mongo -i {raob_file} --mongo-uri {args.mongo_uri} --mongo-db {args.mongo_db} --mongo-col {args.mongo_col}')
	if args.amdar_root != None:
		amdar_file = f'{args.amdar_root}/{time.format("YYYYMMDD")}/{time.format("YYYYMMDDHHmmSS")}.xml'
		if not os.path.isfile(amdar_file):
			print(f'[Warning]: {amdar_file} does not exist.')
		else:
			os.system(f'time {data_translate} -r amdar_cimiss_xml -w mongo -i {amdar_file} --mongo-uri {args.mongo_uri} --mongo-db {args.mongo_db} --mongo-col {args.mongo_col}')
